﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SafeScript.MetaModel
{
    public class Using
    {
        public List<Namespace> Imported = new List<Namespace>();
        public Dictionary<string, Namespace> Alias = new Dictionary<string, Namespace>();
        public Using ParentUsing;
        public Stack<Dictionary<string, object>> Stack = new Stack<Dictionary<string, object>>();

        internal List<ScopeResolver> ImportedTmp = new List<ScopeResolver>();
        internal Dictionary<string, ScopeResolver> AliasTmp = new Dictionary<string, ScopeResolver>();

        public void Resolve(ErrorReport report)
        {
            foreach (string name in this.AliasTmp.Keys)
            {
                ScopeResolver resolver = this.AliasTmp[name];
                object result = resolver.ResolveScope();
                if (result != null)
                {
                    if (result.GetType() != typeof(Namespace))
                    {
                        report.Add(new ErrorEntry(resolver.Location)
                        {
                            Type = ErrorType.NotANamespace,
                            Info = resolver.Ident.ToString()
                        });
                    }
                    else
                        this.Alias[name] = result as Namespace;
                }
                else
                {
                    report.Add(new ErrorEntry(resolver.Location)
                    {
                        Type = ErrorType.UnknownNamespace,
                        Info = resolver.Ident.ToString()
                    });
                }
            }

            foreach (ScopeResolver resolver in this.ImportedTmp)
            {
                object result = resolver.ResolveScope();
                if (result != null)
                {
                    if (result.GetType() != typeof(Namespace))
                    {
                        report.Add(new ErrorEntry(resolver.Location)
                        {
                            Type = ErrorType.NotANamespace,
                            Info = resolver.Ident.ToString()
                        });
                    }
                    else
                        this.Imported.Add(result as Namespace);
                }
                else
                {
                    report.Add(new ErrorEntry(resolver.Location)
                    {
                        Type = ErrorType.UnknownNamespace,
                        Info = resolver.Ident.ToString()
                    });
                }
            }
        }
    }
}
